package com.zhou.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import org.hibernate.EmptyInterceptor;

import java.util.List;
import java.util.Map;

/**
 * @author lcz
 * @desc jpa拦截器
 * @mail lcz_0130@163.com
 * @date 2023/12/28
 */

public class JpaInterceptor extends EmptyInterceptor {
    private static final long serialVersionUID = 7846819379987329908L;

    public static ThreadLocal<List<Map<String, String>>> holder = new ThreadLocal<>();

    @Override
    public String onPrepareStatement(String sql) {
        List<Map<String, String>> tableNames = holder.get();
        if (CollectionUtil.isEmpty(tableNames)) return sql;
        for (Map<String, String> tableName : tableNames) {
            String oldName = tableName.get("oldName");
            String newName = tableName.get("newName");
            if (sql.contains(oldName)) {
                sql = sql.replaceAll(oldName, newName);
            }
        }
        return sql;
    }
}
